package com.xiaoq.matrix.service.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.matrix.weixin.util.WeiXinMaterialVo;
import com.xiaoq.matrix.weixin.util.WeiXinUtil;
import com.xiaoq.qiniu.QiNiuSpaceEnum;
import com.xiaoq.qiniu.UploadUtil;


public class WeiXinTransforUtil {
	
	private static Logger LOG = LoggerFactory.getLogger(WeiXinTransforUtil.class);
	
	/**
	 * 删除html文档中的一些节点更具key（比如key）
	 * @param webPageContent
	 * @return
	 */
	public static String removeEleByKey(String webPageContent,String key){
		if (webPageContent.equals("")) {
			return webPageContent;
		}
		Document doc = Jsoup.parseBodyFragment(webPageContent);;
		Elements links=doc.select(key);
		for(int i=0;i<links.size();i++){
			Element el = links.get(i);
			el.remove();
			
		}
		return doc.html();
	}
	
	/**
	 * 找出html中的所有音频地址列表
	 * @param webPageContent
	 * @return
	 */
	public static List<String> parseHomeWebPage2Audio(String webPageContent){
		List<String> urlList = new ArrayList<>();
		
		if (webPageContent.equals("")) {
			return urlList;
		}
		Document doc = Jsoup.parseBodyFragment(webPageContent);;
		Elements links=doc.select("audio");
		for(int i=0;i<links.size();i++){
			Element link = links.get(i);
			String url = link.attr("src");
			urlList.add(url);
		}
		return urlList;
	}
	
	/**
	 * 找出一个html页面中的所有视屏地址列表
	 * @param webPageContent
	 * @return
	 */
	public static List<String> parseHomeWebPage2Video(String webPageContent){
		List<String> urlList = new ArrayList<>();
		
		if (webPageContent.equals("")) {
			return urlList;
		}
		Document doc = Jsoup.parseBodyFragment(webPageContent);;
		Elements links=doc.select("video");
		for(int i=0;i<links.size();i++){
			Element link = links.get(i);
			String url = link.attr("src");
			urlList.add(url);
		}
		return urlList;
	}
	
	/**
	 * 找出一个html页面中所有图片地址列表
	 * @param webPageContent
	 * @return
	 */
	public static List<String> parseHomeWebPage(String webPageContent){
		List<String> urlList = new ArrayList<>();
		
		if (webPageContent.equals("")) {
			return urlList;
		}
		Document doc = Jsoup.parseBodyFragment(webPageContent);
		Elements links=doc.select("img");
		for(int i=0;i<links.size();i++){
			Element link = links.get(i);
			String url = link.attr("src");
			urlList.add(url);
		}
		return urlList;
	}
	
	/**
	 * 替换文章中的文章
	 * @param content
	 * @param replaceElementMap
	 * @return
	 */
	public static String replaceWebPageElements(String content,Map<String,String> replaceElementMap){
		for(String url:replaceElementMap.keySet()){
			if(StringUtils.isNotEmpty(url)){
				String newPath=replaceElementMap.get(url);
				if(StringUtils.isNotEmpty(newPath)){
					content=content.replace(url, newPath);
				}
			}
		}
		return content;
	}
	public static String replaceWebPageImages(String content,Map<String,String> replaceImgMap){
		for(String url:replaceImgMap.keySet()){
			if(StringUtils.isNotEmpty(url)){
				String newPath=replaceImgMap.get(url);
				if(StringUtils.isNotEmpty(newPath)){
					content=content.replace(url, newPath);
				}
			}
		}
		return content;
	}
	
	/**
	 * 更换一组音频的url
	 * @param videoUrlList
	 * @param accessToken
	 * @return
	 */
	public static Map<String, String> downLoadAudios(List<String> elementsUrlList, String accessToken) {
		Map<String,String> replaceImgMap=new HashMap<String,String>();
		for(int i=0;i<elementsUrlList.size();i++){
			try {
				String elmentUrl=elementsUrlList.get(i);
				String suffnix = null; // 网上下载问价的后缀名
				URL ul = new URL(elmentUrl);
				HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
				String contentType = conn.getContentType();
				String[]ss = contentType.split("/");
				suffnix = ss[1];
				BufferedInputStream bi = new BufferedInputStream(conn.getInputStream());
				String appDir = ResourceUtils.getURL("classpath:").getPath();
				String fileName = new IdGenerator().nextId()+"."+suffnix;
				String fileUrl = appDir+"\\"+fileName;
				FileOutputStream bs = new FileOutputStream(fileUrl);
				byte[] by = new byte[1024];
				int len = 0;
				while((len=bi.read(by))!=-1){
				    bs.write(by,0,len);
				}
				bs.close();
				bi.close();
				File file = new File(fileUrl);
				String imgUrl = UploadUtil.easyUploadBytes(file,file.getName(), QiNiuSpaceEnum.XIAOQ_MATRIX.getName().toLowerCase(),
						QiNiuSpaceEnum.XIAOQ_MATRIX.getDomain());
				replaceImgMap.put(elmentUrl, imgUrl);
				
				WeiXinMaterialVo weixinMaterial = WeiXinUtil.addMaterial("voice", file, accessToken);
				file.delete();
			} catch (Exception e) {
				e.printStackTrace();
			} 
			
		}
		return replaceImgMap;
	}
	
	/**
	 * 更换一组视屏的url
	 * @param videoUrlList
	 * @param accessToken
	 * @return
	 */
	public static Map<String, String> downLoadVedios(List<String> elementsUrlList, String accessToken) {
		Map<String,String> replaceImgMap=new HashMap<String,String>();
		for(int i=0;i<elementsUrlList.size();i++){
			try {
				String elmentUrl=elementsUrlList.get(i);
				String suffnix = null; // 网上下载问价的后缀名
				URL ul = new URL(elmentUrl);
				HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
				String contentType = conn.getContentType();
				String[]ss = contentType.split("/");
				suffnix = ss[1];
				BufferedInputStream bi = new BufferedInputStream(conn.getInputStream());
				String appDir = ResourceUtils.getURL("classpath:").getPath();
				String fileName = new IdGenerator().nextId()+"."+suffnix;
				String fileUrl = appDir+"\\"+fileName;
				System.out.println(fileUrl);
				FileOutputStream bs = new FileOutputStream(fileUrl);
				byte[] by = new byte[1024];
				int len = 0;
				while((len=bi.read(by))!=-1){
				    bs.write(by,0,len);
				}
				bs.close();
				bi.close();
				File file = new File(fileUrl);
				String imgUrl = UploadUtil.easyUploadBytes(file,file.getName(), QiNiuSpaceEnum.XIAOQ_MATRIX.getName().toLowerCase(),
						QiNiuSpaceEnum.XIAOQ_MATRIX.getDomain());
				replaceImgMap.put(elmentUrl, imgUrl);
				file.delete();
			} catch (Exception e) {
				e.printStackTrace();
			} 
			
		}
		return replaceImgMap;
	}
	
	/**
	 * 更换一组图片的url
	 * @param imgUrlList
	 * @param accessToken
	 * @return
	 */
	public static Map<String,String> downLoadImags(List<String> imgUrlList,String accessToken){
		Map<String,String> replaceImgMap=new HashMap<String,String>();
		for(int i=0;i<imgUrlList.size();i++){
			try {
				String imUrl=imgUrlList.get(i);
				String suffnix = null; // 网上下载问价的后缀名
				LOG.info("要交换的图片地址"+imUrl);
				URL ul = new URL(imUrl);
				HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
				String contentType = conn.getContentType();
				String[]ss = contentType.split("/");
				suffnix = ss[1];
				BufferedInputStream bi = new BufferedInputStream(conn.getInputStream());
				String appDir = ResourceUtils.getURL("classpath:").getPath();
				String fileName = new IdGenerator().nextId()+"."+suffnix;
				String fileUrl = appDir+"\\"+fileName;
				FileOutputStream bs = new FileOutputStream(fileUrl);
				byte[] by = new byte[1024];
				int len = 0;
				while((len=bi.read(by))!=-1){
				    bs.write(by,0,len);
				}
				bs.close();
				bi.close();
				File file = new File(fileUrl);
				String imgUrl = WeiXinUtil.uploadImage(file, accessToken);
				replaceImgMap.put(imUrl, imgUrl);
				file.delete();
			} catch (Exception e) {
				LOG.error(e.getMessage(),e);
			} 
			
//			URL url = null;
//			try {
//				url = new URL(imUrl);
//			} catch (MalformedURLException e1) {
//				LOG.error(e1.getMessage(),e1);
//			}  
//	        //打开链接  
//	        HttpURLConnection conn = null;
//			try {
//				conn = (HttpURLConnection)url.openConnection();
//			} catch (IOException e1) {
//				LOG.error(e1.getMessage(),e1);
//			}  
//	        //设置请求方式为"GET"  
//	        try {
//				conn.setRequestMethod("GET");
//			} catch (ProtocolException e1) {
//				LOG.error(e1.getMessage(),e1);
//			}  
//	        //超时响应时间为5秒  
//	        conn.setConnectTimeout(5 * 1000);  
//	        //通过输入流获取图片数据  
//	        InputStream inStream = null;
//			try {
//				inStream = conn.getInputStream();
//			} catch (IOException e1) {
//				LOG.error(e1.getMessage(),e1);
//			}  
//			
//					try {
//						String appDir = ResourceUtils.getURL("classpath:").getPath();
//						File file = new File(appDir+"\\img.png");
//						FileUtils.copyToFile(inStream, file);
//						String imgUrl = WeiXinUtil.uploadImage(file, accessToken);
//						replaceImgMap.put(imUrl, imgUrl);
//						//用完一定要删
//						file.delete();
//					} catch (Exception e) {
//						LOG.error(e.getMessage(),e);
//					}
			
			
		}
		return replaceImgMap;
	}
	
	/**
	 * 主要是想根据我们的主图url 获取微信的主图媒体Id
	 * @param imgUrlList
	 * @param accessToken
	 * @return
	 */
	public static WeiXinMaterialVo transForMatrial(String imgUrl, String accessToken) {
		
		WeiXinMaterialVo weiXInMaterialVo = null;
		try {
			String suffnix = null; // 网上下载问价的后缀名
			URL ul = new URL(imgUrl);
			HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
			String contentType = conn.getContentType();
			String[]ss = contentType.split("/");
			suffnix = ss[1];
			BufferedInputStream bi = new BufferedInputStream(conn.getInputStream());
			String appDir = ResourceUtils.getURL("classpath:").getPath();
			String fileName = new IdGenerator().nextId()+"."+suffnix;
			String fileUrl = appDir+"\\"+fileName;
			FileOutputStream bs = new FileOutputStream(fileUrl);
			byte[] by = new byte[1024];
			int len = 0;
			while((len=bi.read(by))!=-1){
			    bs.write(by,0,len);
			}
			bs.close();
			bi.close();
			File file = new File(fileUrl);
			weiXInMaterialVo = WeiXinUtil.addMaterial("image", file, accessToken);
			// 用完一定要删
			file.delete();
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}

		return weiXInMaterialVo;
	}
}
